#import  <appkit/Application.h>
#import  <appkit/Control.h>
#import  <appkit/Matrix.h>
#import  <appkit/tiff.h>
#import  "TiffSavePanel.h"

#define  Tag_None	0
#define  Tag_LZW	1
#define  Tag_JPEG	2

@implementation TiffSavePanel


#define  SqDelta	0.001

static float sqroot(float x) // sqrt() ; low precision
{
	float s, old;

	if (x <= SqDelta)
		return 0.0;
	s = (x > 1.0) ? x : 1.0;
	do {
		old = s;
		s = (x / s + s) / 2.0;
	} while (old - s > SqDelta);
	return old;
}


- init:(float)factor jpeg: (BOOL)flag
{
	if (accessoryView == nil) {
		[NXApp loadNibSection:"TiffAccessory.nib" owner:self];
		[self setAccessoryView: [accessory contentView]];
	}
	if (factor > 255.0) factor = 255.0;
	else if (factor < 0.0) factor = 0.0;
	[JPEGtext setIntValue: (int)factor];
	[JPEGslider setFloatValue: sqroot(factor)];
	JPEGselectable = flag;
	[[compButton findCellWithTag: Tag_JPEG] setEnabled: JPEGselectable];
	[JPEGslider setEnabled: NO];
	return self;
}

- compressType:(int *)type with:(float *)factor
{
	*type = NX_TIFF_COMPRESSION_NONE;

	*factor = 0.0;
	switch ([compButton selectedTag]) {
	case Tag_None:
		*type = NX_TIFF_COMPRESSION_NONE;
		break;
	case Tag_LZW:
		*type = NX_TIFF_COMPRESSION_LZW;
		break;
	case Tag_JPEG:
		*type = NX_TIFF_COMPRESSION_JPEG;
		*factor = (float)[JPEGtext intValue];
		break;
	}
	return self;
}

- takeFloatValueFrom: sender
{
	/* 0 -  6 (0 -  36)   step 1
	 *   - 10 (  - 100)   step 2
	 *   - 16 (  - 255)   step 5
	 */
	int n;
	float r = [sender floatValue];
	if (r <= 6.0) n = (int)(r * r);
	else if (r <= 10.0) n = (int)(r * r) & ~1;
	else {
		n = (int)(r * r) / 5 * 5;
		if (n > 255) n = 255;
	}
	[JPEGtext setIntValue: n];
	return self;
}

- buttonChanged: sender
{
	if (JPEGselectable) {
		BOOL flag = ([compButton selectedTag] == Tag_JPEG);
		[JPEGslider setEnabled: flag];
	}
	return self;
}

@end
